<template>
  <div class="h-screen flex">
    <!-- 左侧品牌展示区 -->
    <div class="w-1/2 gradient-bg text-white flex flex-col justify-center items-center text-center p-12 relative z-10">
      <div class="flex flex-col items-center">
        <div class="w-24 h-24 rounded-full mb-6 overflow-hidden" :class="{ 'bg-white': !logoUrl }">
          <template v-if="logoUrl">
            <img :src="logoUrl" alt="品牌图" class="w-full h-full object-cover" />
          </template>
        </div>
        <h1 class="text-4xl font-bold mb-3 text-white">校园快递代拿</h1>
        <p class="text-lg text-blue-100">安全、快捷、方便的快递代拿体验，让校园生活更轻松</p>
      </div>

      <div class="space-y-6 mt-12 w-full max-w-xl text-left">
        <div class="flex items-start gap-4">
          <div class="w-12 h-12 bg-white bg-opacity-20 rounded-lg flex items-center justify-center flex-shrink-0">
            <span class="w-6 h-6">🔒</span>
          </div>
          <div>
            <h3 class="text-lg font-semibold mb-1">安全保障</h3>
            <p class="text-sm text-blue-100">实名认证，全程追踪，保障您的快递安全</p>
          </div>
        </div>
        <div class="flex items-start gap-4">
          <div class="w-12 h-12 bg-white bg-opacity-20 rounded-lg flex items-center justify-center flex-shrink-0">
            <span class="w-6 h-6">⚡</span>
          </div>
          <div>
            <h3 class="text-lg font-semibold mb-1">快速配送</h3>
            <p class="text-sm text-blue-100">校内专人配送，最快30分钟送达</p>
          </div>
        </div>
        <div class="flex items-start gap-4">
          <div class="w-12 h-12 bg-white bg-opacity-20 rounded-lg flex items-center justify-center flex-shrink-0">
            <span class="w-6 h-6">📱</span>
          </div>
          <div>
            <h3 class="text-lg font-semibold mb-1">便捷操作</h3>
            <p class="text-sm text-blue-100">在线下单，实时追踪，一键完成代拿服务</p>
          </div>
        </div>
      </div>

      <!-- 底部学校标签区域已按要求移除 -->
    </div>

    <!-- 右侧注册表单区 -->
    <div class="w-1/2 bg-gray-50 flex items-center justify-center p-12">
      <div class="w-full max-w-md">
        <div class="mb-8">
          <h2 class="text-3xl font-bold text-gray-900 mb-2">创建账号</h2>
          <p class="text-gray-500">填写以下信息完成注册</p>
        </div>

        <form class="space-y-5" @submit.prevent="handleRegister">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">手机号</label>
            <input type="tel" v-model="phone" placeholder="请输入手机号" maxlength="11" class="w-full pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none transition">
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">验证码</label>
            <div class="flex gap-3">
              <div class="flex-1">
                <input type="text" v-model="code" placeholder="请输入验证码" maxlength="6" class="w-full pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none transition">
              </div>
              <button type="button" class="px-6 py-3 border border-blue-500 text-blue-500 rounded-lg hover:bg-blue-50 transition font-medium whitespace-nowrap" :disabled="countdown>0" @click="getVerificationCode">
                {{ countdown > 0 ? `重新发送(${countdown}s)` : '获取验证码' }}
              </button>
            </div>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">设置密码</label>
            <input type="password" v-model="password" placeholder="请设置6-20位密码" class="w-full pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none transition">
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">确认密码</label>
            <input type="password" v-model="confirmPassword" placeholder="请再次输入密码" class="w-full pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none transition">
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">昵称 <span class="text-red-500">*</span></label>
            <input 
              type="text" 
              v-model="nickname" 
              @input="checkNickname"
              placeholder="请输入您的昵称（2-20个字符）" 
              maxlength="20"
              :class="[
                'w-full pr-4 py-3 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none transition',
                nicknameStatus === 'checking' ? 'border-gray-300' : 
                nicknameStatus === 'error' ? 'border-red-500' : 
                nicknameStatus === 'success' ? 'border-green-500' : 'border-gray-300'
              ]"
            />
            <div v-if="nicknameStatus === 'checking'" class="text-xs text-blue-600 mt-1 flex items-center gap-1">
              <svg class="animate-spin h-3 w-3" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              正在检查...
            </div>
            <div v-else-if="nicknameStatus === 'error'" class="text-xs text-red-500 mt-1">
              {{ nicknameError || '该昵称已被使用，请更换' }}
            </div>
            <div v-else-if="nicknameStatus === 'success'" class="text-xs text-green-600 mt-1 flex items-center gap-1">
              <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>
              昵称可用
            </div>
            <div v-else-if="nickname && nickname.length < 2" class="text-xs text-gray-500 mt-1">
              昵称至少需要2个字符
            </div>
          </div>

          <div class="flex items-start gap-2">
            <input type="checkbox" id="agreement" v-model="agree" class="mt-1 w-4 h-4 text-blue-500 border-gray-300 rounded focus:ring-blue-500">
            <label for="agreement" class="text-sm text-gray-600">注册即表示同意我们的<a href="#" class="text-blue-500 hover:underline">用户协议</a>和<a href="#" class="text-blue-500 hover:underline">隐私政策</a></label>
          </div>

          <button type="submit" class="w-full py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition font-medium text-lg">注册</button>

          <div class="text-center text-sm text-gray-600">已有账号？<a href="#" class="text-blue-500 hover:underline font-medium" @click.prevent="goToLogin">立即登录</a></div>
        </form>

        

        <div class="mt-8 text-center text-xs text-gray-400">
          <p>© 2023 校园快递代拿 版权所有 | 隐私政策 | 使用条款</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
// 将图片放到 src/assets/register-logo.png 后，下面的导入会自动生效
import registerLogo from '@/../头像.jpg'

export default {
  name: 'Register',
  data() {
    return {
      logoUrl: registerLogo || '',
      phone: '',
      code: '',
      password: '',
      confirmPassword: '',
      nickname: '',
      nicknameStatus: '', // 'checking', 'success', 'error', ''
      nicknameError: '',
      nicknameCheckTimer: null,
      countdown: 0,
      timer: null,
      agree: false
    }
  },
  methods: {
    // 获取验证码
    async getVerificationCode() {
      // 更宽松的手机号验证：11位数字，以1开头
      const phoneRegex = /^1\d{10}$/

      if (!this.phone) {
        ElMessage.warning('请输入手机号')
        return
      }

      if (!phoneRegex.test(this.phone)) {
        ElMessage.warning('请输入正确的11位手机号（以1开头）')
        return
      }

      try {
        const response = await fetch('/api/auth/send-sms', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            phone: this.phone
          })
        })

        const result = await response.json()

        if (result.success) {
          // 获取验证码（优先使用 debugCode，兼容 smsCode）
          const verificationCode = result.data?.debugCode || result.data?.smsCode || ''
          
          // 显示验证码消息（开发模式下显示验证码）
          if (verificationCode) {
            ElMessage({
              message: `验证码已发送: ${verificationCode}`,
              type: 'success',
              duration: 5000,
              showClose: true
            })
          } else {
            ElMessage.success(result.message || '验证码已发送')
          }
          
          this.countdown = 60
          this.timer = setInterval(() => {
            this.countdown--
            if (this.countdown <= 0) {
              clearInterval(this.timer)
            }
          }, 1000)
        } else {
          ElMessage.error(result.message || '发送验证码失败')
        }
      } catch (error) {
        console.error('发送验证码错误:', error)
        ElMessage.error('网络错误，请重试')
      }
    },

    // 检查昵称是否可用
    async checkNickname() {
      const nickname = this.nickname.trim()
      
      // 清除之前的定时器
      if (this.nicknameCheckTimer) {
        clearTimeout(this.nicknameCheckTimer)
      }

      // 如果昵称为空或长度不够，不检查
      if (!nickname || nickname.length < 2) {
        this.nicknameStatus = ''
        this.nicknameError = ''
        return
      }

      if (nickname.length > 20) {
        this.nicknameStatus = 'error'
        this.nicknameError = '昵称不能超过20个字符'
        return
      }

      // 防抖：延迟500ms后检查
      this.nicknameStatus = 'checking'
      this.nicknameCheckTimer = setTimeout(async () => {
        try {
          const response = await fetch('/api/auth/check-nickname', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({ nickname })
          })

          const result = await response.json()

          if (result.success) {
            if (result.data.available) {
              this.nicknameStatus = 'success'
              this.nicknameError = ''
            } else {
              this.nicknameStatus = 'error'
              this.nicknameError = result.message || '该昵称已被使用，请更换'
            }
          } else {
            this.nicknameStatus = 'error'
            this.nicknameError = result.message || '检查失败'
          }
        } catch (error) {
          console.error('检查昵称失败:', error)
          this.nicknameStatus = ''
          this.nicknameError = ''
        }
      }, 500)
    },
    
    // 注册
    async handleRegister() {
      if (!this.phone || !this.code || !this.password) {
        ElMessage.warning('请填写完整信息')
        return
      }

      if (!this.nickname || this.nickname.trim().length < 2) {
        ElMessage.warning('请输入昵称（2-20个字符）')
        return
      }

      if (this.nickname.trim().length > 20) {
        ElMessage.warning('昵称不能超过20个字符')
        return
      }

      if (this.nicknameStatus !== 'success') {
        ElMessage.warning('昵称不可用，请更换后再试')
        return
      }

      if (this.password !== this.confirmPassword) {
        ElMessage.warning('两次输入的密码不一致')
        return
      }

      if (this.password.length < 6) {
        ElMessage.warning('密码长度至少6位')
        return
      }

      if (!this.agree) {
        ElMessage.warning('请先阅读并同意用户协议与隐私政策')
        return
      }

      try {
        const response = await fetch('/api/auth/register-with-sms', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            phone: this.phone,
            smsCode: this.code,
            password: this.password,
            nickname: this.nickname.trim()
          })
        })

        const result = await response.json()

        if (result.success) {
          ElMessage.success('注册成功！')
          
          // 跳转到登录
          this.$router.push('/login')
        } else {
          ElMessage.error(result.message || '注册失败')
        }
      } catch (error) {
        console.error('注册错误:', error)
        ElMessage.error('网络错误，请重试')
      }
    },

    // 跳转到登录页面
    goToLogin() {
      this.$router.push('/login')
    }
  },
  beforeUnmount() {
    if (this.timer) {
      clearInterval(this.timer)
    }
    if (this.nicknameCheckTimer) {
      clearTimeout(this.nicknameCheckTimer)
    }
  }
}
</script>

<style scoped>
.gradient-bg {
  background: linear-gradient(135deg, #4A90E2 0%, #357ABD 100%);
  position: relative;
  overflow: hidden;
}
.gradient-bg::before {
  content: '';
  position: absolute;
  width: 600px;
  height: 600px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  top: -200px;
  right: -100px;
}
.gradient-bg::after {
  content: '';
  position: absolute;
  width: 400px;
  height: 400px;
  background: rgba(255, 255, 255, 0.08);
  border-radius: 50%;
  bottom: -150px;
  left: -100px;
}
.register-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.register-container {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  width: 100%;
  max-width: 420px;
  padding: 40px 30px;
}

.logo-section {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  width: 80px;
  height: 80px;
  border-radius: 16px;
  margin: 0 auto 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  background: linear-gradient(135deg, #4a90e2, #67b26f);
}

.logo-placeholder {
  font-size: 40px;
  color: white;
}

h1 {
  color: #333;
  font-size: 24px;
  margin-bottom: 8px;
}

.subtitle {
  color: #666;
  font-size: 14px;
}

.register-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

label {
  color: #555;
  font-size: 14px;
  font-weight: 500;
}

input {
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s;
}

input:focus {
  border-color: #4a90e2;
  outline: none;
}

.register-btn {
  background: linear-gradient(135deg, #4a90e2, #5fa8ff);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 14px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: opacity 0.3s;
  margin-top: 10px;
}

.register-btn:hover {
  opacity: 0.9;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.login-link a {
  color: #4a90e2;
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}

.code-group {
  display: flex;
  gap: 10px;
}

.code-input {
  flex: 1;
}

.get-code-btn {
  background: #f0f2f5;
  color: #4a90e2;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 12px 15px;
  font-size: 14px;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.3s;
}

.get-code-btn:hover:not(:disabled) {
  background: #e6e9ed;
}

.get-code-btn:disabled {
  background: #f5f5f5;
  color: #999;
  cursor: not-allowed;
}
</style>